package fa.wangxing.leaf.Controller;

import fa.wangxing.leaf.Service.UserService;
import fa.wangxing.leaf.pojo.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public String register(@RequestParam("userName") String userName,@RequestParam("password") String password, ModelMap model,HttpSession session) {
        if(userService.isuser(userName)){
            model.put("msg","该用户名已被占用，注册失败");
            return "register";
        }else {
            User user = new User();
            user.setUserName(userName);
            user.setPassword(password);
            System.out.println(user);
            userService.register(user);
            return login(userName,password,model,session);
            }
        }
    @GetMapping("/login")
    public String login(String userName, String password, ModelMap m, HttpSession session) {
        User user = userService.login(userName, password);
        if (user != null) {
            session.setAttribute("session_user", user);
            m.put("src", "/images/yuxiangrousi.jpg");
            System.out.println();
            return "main";
        } else {
            //传递request作用域数据
            m.put("msg", "账号或密码错误,登录失败");
            return "login";
        }
    }
    @RequestMapping("/toregister")
    public String toregisteer() {
        return "register";
    }

    @RequestMapping("/tologin")
    public String login() {
        return "login";
    }



    @RequestMapping("/tomain")
    public String tomain() {
        return "main";
    }
}
